package cn.lichenfei.fxui.controls.skin;

import cn.lichenfei.fxui.controls.CFRadioButton;
import com.sun.javafx.scene.control.behavior.BehaviorBase;
import com.sun.javafx.scene.control.behavior.ToggleButtonBehavior;

import javafx.animation.ScaleTransition;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.SkinBase;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Circle;
import javafx.util.Duration;

public class CFRadioButtonSkin extends SkinBase<CFRadioButton> {

    private HBox container;
    private StackPane leftContainer;
    private Circle radio;
    private Circle dot;
    private Label label;
    // 动画
    private ScaleTransition scaleTransition;

    private final BehaviorBase<RadioButton> behavior;


    public CFRadioButtonSkin(CFRadioButton control) {
        super(control);
        behavior = new ToggleButtonBehavior<>(control);
        createNode(control);
        getChildren().setAll(container);
        setAnimationInfo();
    }

    @Override
    public void dispose() {
        super.dispose();
        if (behavior != null) {
            behavior.dispose();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void layoutChildren(final double x, final double y,
                                  final double w, final double h) {
        super.layoutChildren(x, y, w, h);
    }

    private void createNode(CFRadioButton cfRadioButton) {
        radio = new Circle(9);
        dot = new Circle();
        dot.radiusProperty().bind(radio.radiusProperty().subtract(4));
        leftContainer = new StackPane(radio, dot);
        label = new Label();
        label.textProperty().bind(cfRadioButton.textProperty());
        container = new HBox(leftContainer, label);
        //class
        radio.getStyleClass().add("radio");
        dot.getStyleClass().add("dot");
        //label.getStyleClass().add("label");
        leftContainer.getStyleClass().add("left-container");
        container.getStyleClass().add("container");
        //
    }

    private void setAnimationInfo() {
        // 测试：
        CFRadioButton skinnable = getSkinnable();
        if (!skinnable.isSelected()) {
            dot.setScaleX(0);
            dot.setScaleY(0);
        }
        scaleTransition = new ScaleTransition(Duration.millis(200), dot);
        skinnable.selectedProperty().addListener((observableValue, aBoolean, t1) -> {
            scaleTransition.stop();
            scaleTransition.setToX(t1 ? 1 : 0);
            scaleTransition.setToY(t1 ? 1 : 0);
            scaleTransition.setFromX(t1 ? 0 : 1);
            scaleTransition.setFromY(t1 ? 0 : 1);
            scaleTransition.play();
        });
    }
}
